import os
import json
import webbrowser
from flask import Flask, render_template, jsonify, send_from_directory
from threading import Timer

app = Flask(__name__)

# 视频文件夹路径
VIDEO_FOLDER = 'static/smart-agri-videos'
VIDEO_FOLDER_PATH = os.path.join(app.root_path, VIDEO_FOLDER)

# 视频文件扩展名
VIDEO_EXTENSIONS = ['.mp4', '.webm', '.ogg', '.mov']

# 首页路由
@app.route('/')
def index():
    return render_template('index.html')

# 视频列表API
@app.route('/api/video_list')
def get_video_list():
    """获取视频文件列表"""
    try:
        # 检查视频文件夹是否存在
        if not os.path.exists(VIDEO_FOLDER_PATH):
            return jsonify({"error": "视频文件夹不存在"}), 404
        
        # 读取文件夹内容
        files = os.listdir(VIDEO_FOLDER_PATH)
        
        # 过滤视频文件
        video_files = [f for f in files if os.path.splitext(f)[1].lower() in VIDEO_EXTENSIONS]
        
        # 生成视频源数据
        video_sources = []
        for i, file in enumerate(video_files):
            # 从文件名提取视频名称（去掉扩展名）
            video_name = os.path.splitext(file)[0]
            video_name = video_name.replace('-', ' ').title()
            
            # 模拟视频状态
            status = 'online'
            if i == 2:
                status = 'warning'
            elif i == 3:
                status = 'alert'
            
            # 构建视频URL
            video_url = f"/static/smart-agri-videos/{file}"
            
            video_sources.append({
                "id": i + 1,
                "name": video_name,
                "thumbnail": "https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc/pc/super_tool/1b322b8549714162923b1c3ea739e892~tplv-a9rns2rl98-image.image?rcl=2025102814460593BEE518A94BE5BB7B1F&rk3s=8e244e95&rrcfp=f06b921b&x-expires=1764225990&x-signature=KS%2FZFXHaZV0JLHYOTNAZiFCU9v8%3D",
                "videoUrl": video_url,
                "status": status,
                "lastUpdated": "2025-07-21 15:30"
            })
        
        # 保存视频列表到JSON文件
        with open(os.path.join(app.root_path, 'video_list.json'), 'w') as f:
            json.dump(video_sources, f, ensure_ascii=False, indent=2)
        
        return jsonify(video_sources)
    
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 视频文件路由
@app.route('/static/smart-agri-videos/<path:filename>')
def serve_video_file(filename):
    """提供视频文件"""
    return send_from_directory(VIDEO_FOLDER_PATH, filename)

# 视频列表JSON文件路由
@app.route('/video_list.json')
def video_list_json():
    """提供视频列表JSON文件"""
    try:
        with open(os.path.join(app.root_path, 'video_list.json'), 'r') as f:
            video_list = json.load(f)
        return jsonify(video_list)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 打开浏览器
def open_browser():
    """在服务器启动后自动打开浏览器"""
    webbrowser.open_new('http://127.0.0.1:8004/')

if __name__ == '__main__':
    # 启动服务器前延迟2秒打开浏览器
    Timer(2, open_browser).start()
    
    # 启动Flask服务器，设置host为0.0.0.0以允许局域网访问
    app.run(debug=True, use_reloader=False, host='0.0.0.0', port=8004)
